<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('log_errors', 1);
ini_set('error_log', '/tmp/php_errors.log');

echo "=== 系统管理页面调试 ===<br>";
echo "开始调试...<br>";

try {
    echo "1. 启动Session...<br>";
    if (session_status() == PHP_SESSION_NONE) {
        session_start();
    }
    echo "✓ Session启动成功<br>";

    echo "2. 检查登录状态...<br>";
    if (!isset($_SESSION['user_id']) || !isset($_SESSION['username'])) {
        echo "✗ 用户未登录，需要重定向<br>";
        // header('Location: index.php');
        // exit();
    } else {
        echo "✓ 用户已登录: " . $_SESSION['user_id'] . "<br>";
    }

    echo "3. 包含数据库文件...<br>";
    if (file_exists('database.php')) {
        require_once 'database.php';
        echo "✓ 数据库文件包含成功<br>";
    } else {
        echo "✗ database.php文件不存在<br>";
        throw new Exception("database.php文件不存在");
    }

    echo "4. 检查数据库连接...<br>";
    if (isset($conn) && $conn instanceof mysqli) {
        echo "✓ 数据库连接变量存在且类型正确<br>";

        // 测试连接
        if ($conn->ping()) {
            echo "✓ 数据库连接正常<br>";
        } else {
            echo "✗ 数据库连接失败<br>";
        }
    } else {
        echo "✗ 数据库连接变量不存在或类型错误<br>";
        throw new Exception("数据库连接失败");
    }

    echo "5. 测试基本查询...<br>";
    $test_query = "SELECT COUNT(*) as count FROM staff";
    $result = $conn->query($test_query);
    if ($result) {
        $row = $result->fetch_assoc();
        echo "✓ 员工数量查询成功: " . $row['count'] . "<br>";
    } else {
        echo "✗ 员工查询失败: " . $conn->error . "<br>";
    }

    echo "6. 测试角色查询...<br>";
    $roles_query = "SELECT COUNT(*) as count FROM user_roles";
    $roles_result = $conn->query($roles_query);
    if ($roles_result) {
        $roles_row = $roles_result->fetch_assoc();
        echo "✓ 角色数量查询成功: " . $roles_row['count'] . "<br>";
    } else {
        echo "✗ 角色查询失败: " . $conn->error . "<br>";
    }

    echo "7. 检查导航文件...<br>";
    if (file_exists('common/navigation.php')) {
        echo "✓ navigation.php文件存在<br>";
        // 暂时不包含，可能导致错误
        // include_once 'common/navigation.php';
    } else {
        echo "✗ common/navigation.php文件不存在<br>";
    }

    echo "<br>=== 基本功能测试完成 ===<br>";
    echo "如果看到这条消息，说明基本功能正常<br>";

} catch (Exception $e) {
    echo "✗ 发生错误: " . $e->getMessage() . "<br>";
    echo "错误文件: " . $e->getFile() . "<br>";
    echo "错误行号: " . $e->getLine() . "<br>";
}

// 显示PHP错误信息
if (function_exists('error_get_last')) {
    $last_error = error_get_last();
    if ($last_error) {
        echo "<br>=== PHP错误信息 ===<br>";
        echo "类型: " . $last_error['type'] . "<br>";
        echo "消息: " . $last_error['message'] . "<br>";
        echo "文件: " . $last_error['file'] . "<br>";
        echo "行号: " . $last_error['line'] . "<br>";
    }
}

echo "<br>调试完成";
?>